<template>
  <div class="p-2">
    <!-- 统计卡片 -->
    <el-row :gutter="10" class="mb-4">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">待风控审核</div>
            <div class="stat-value text-warning">{{ pendingCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-label">今日已审核</div>
            <div class="stat-value text-info">{{ todayAuditedCount }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="queryParams.userId"
            placeholder="请输入用户ID"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="orderList"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="订单号" prop="orderNo" width="180" />
        <el-table-column label="用户ID" prop="userId" width="100" />
        <el-table-column label="项目名称" prop="projectName" width="150" show-overflow-tooltip />
        <el-table-column label="医院" prop="hospitalName" width="150" show-overflow-tooltip />
        <el-table-column label="订单金额" prop="totalAmount" width="120" align="right">
          <template #default="scope">
            <span class="text-danger">¥{{ scope.row.totalAmount?.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="首付金额" prop="downPayment" width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.downPayment?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="贷款金额" prop="loanAmount" width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.loanAmount?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="分期期数" prop="periods" width="100" align="center">
          <template #default="scope">
            {{ scope.row.periods }}期
          </template>
        </el-table-column>
        <el-table-column label="银行卡信息" width="200">
          <template #default="scope">
            <div v-if="scope.row.bankName">
              <div>{{ scope.row.bankName }}</div>
              <div class="text-info">{{ scope.row.cardNo }}</div>
            </div>
            <span v-else class="text-secondary">未绑定</span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" prop="createTime" width="160" />
        <el-table-column label="操作" fixed="right" width="200" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="View"
              @click="handleDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="success"
              link
              icon="Check"
              @click="handleAudit(scope.row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      destroy-on-close
    >
      <el-descriptions :column="2" border v-if="currentOrder">
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentOrder.userId }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ currentOrder.projectName }}</el-descriptions-item>
        <el-descriptions-item label="医院">{{ currentOrder.hospitalName }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">
          <span class="text-danger">¥{{ currentOrder.totalAmount?.toFixed(2) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="首付金额">
          ¥{{ currentOrder.downPayment?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="贷款金额">
          ¥{{ currentOrder.loanAmount?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="分期期数">
          {{ currentOrder.periods }}期
        </el-descriptions-item>
        <el-descriptions-item label="月利率">
          {{ (currentOrder.interestRate * 100)?.toFixed(2) }}%
        </el-descriptions-item>
        <el-descriptions-item label="月供金额">
          ¥{{ currentOrder.monthlyAmount?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="总利息">
          ¥{{ currentOrder.totalInterest?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="总还款">
          ¥{{ currentOrder.totalRepayment?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="银行卡">
          {{ currentOrder.bankName }} {{ currentOrder.cardNo }}
        </el-descriptions-item>
        <el-descriptions-item label="提交时间">
          {{ currentOrder.createTime }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 风险评分 -->
      <el-divider content-position="left">风险评分</el-divider>
      <div v-if="riskScore" class="risk-score-panel">
        <div class="score-display">
          <div class="score-label">风险评分</div>
          <div class="score-value" :class="getScoreClass(riskScore.riskScore)">
            {{ riskScore.riskScore }}
          </div>
        </div>
        <el-descriptions :column="2" border class="mt-3">
          <el-descriptions-item label="基础分">{{ riskScore.scoreDetails.baseScore }}</el-descriptions-item>
          <el-descriptions-item label="实名认证">
            <el-tag :type="riskScore.scoreDetails.idVerified ? 'success' : 'danger'">
              {{ riskScore.scoreDetails.idVerified ? '已认证(+10)' : '未认证' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="手机认证">
            <el-tag :type="riskScore.scoreDetails.phoneVerified ? 'success' : 'danger'">
              {{ riskScore.scoreDetails.phoneVerified ? '已认证(+10)' : '未认证' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="银行卡认证">
            <el-tag :type="riskScore.scoreDetails.bankcardVerified ? 'success' : 'danger'">
              {{ riskScore.scoreDetails.bankcardVerified ? '已认证(+10)' : '未认证' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="逾期记录">
            <el-tag :type="riskScore.scoreDetails.hasOverdue ? 'danger' : 'success'">
              {{ riskScore.scoreDetails.hasOverdue ? `有逾期(${riskScore.scoreDetails.overdueCount}次, -${riskScore.scoreDetails.overdueCount * 5})` : '无逾期' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="success" @click="handleAuditFromDetail">审核</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="风控审核"
      width="600px"
      destroy-on-close
      @close="resetAuditForm"
    >
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="订单号">
          <span>{{ currentOrder?.orderNo }}</span>
        </el-form-item>
        <el-form-item label="风险评分">
          <span :class="getScoreClass(riskScore?.riskScore || 0)" style="font-size: 24px; font-weight: bold;">
            {{ riskScore?.riskScore || 0 }}
          </span>
        </el-form-item>
        <el-form-item label="审核结果" prop="passed">
          <el-radio-group v-model="auditForm.passed">
            <el-radio :value="true">通过</el-radio>
            <el-radio :value="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="rejectReason" v-if="auditForm.passed === false">
          <el-input
            v-model="auditForm.rejectReason"
            type="textarea"
            :rows="3"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入审核备注（选填）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="OrderRiskAudit">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import {
  listOrder,
  getOrder,
  riskAudit,
  calculateRiskScore,
  type OrderQuery,
  type OrderVO,
  type RiskAuditRequest,
  type RiskScoreResult
} from '@/api/beauty/order';

const loading = ref(false);
const total = ref(0);
const orderList = ref<OrderVO[]>([]);
const pendingCount = ref(0);
const todayAuditedCount = ref(0);
const detailDialogVisible = ref(false);
const auditDialogVisible = ref(false);
const currentOrder = ref<OrderVO | null>(null);
const riskScore = ref<RiskScoreResult | null>(null);

const queryFormRef = ref<FormInstance>();
const auditFormRef = ref<FormInstance>();

const queryParams = reactive<OrderQuery>({
  pageNum: 1,
  pageSize: 10,
  orderStatus: '0', // 待风控审核
});

const auditForm = reactive<RiskAuditRequest>({
  orderId: 0,
  passed: true,
  riskScore: 0,
  auditRemark: '',
  rejectReason: ''
});

const auditRules = reactive<FormRules>({
  passed: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  rejectReason: [
    {
      required: true,
      message: '请输入拒绝原因',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (auditForm.passed === false && !value) {
          callback(new Error('请输入拒绝原因'));
        } else {
          callback();
        }
      }
    }
  ]
});

/** 查询订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams)
    .then((res) => {
      orderList.value = res.data.rows;
      total.value = res.data.total;
      pendingCount.value = res.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: OrderVO[]) {
  // 可以在这里处理批量操作
}

/** 查看详情 */
async function handleDetail(row: OrderVO) {
  currentOrder.value = row;
  detailDialogVisible.value = true;

  // 加载风险评分
  try {
    const res = await calculateRiskScore(row.orderId);
    riskScore.value = res.data;
  } catch (error) {
    console.error('获取风险评分失败:', error);
  }
}

/** 审核操作 */
async function handleAudit(row: OrderVO) {
  currentOrder.value = row;

  // 加载风险评分
  try {
    const res = await calculateRiskScore(row.orderId);
    riskScore.value = res.data;
    auditForm.orderId = row.orderId;
    auditForm.riskScore = res.data.riskScore;
    auditForm.passed = true;
    auditDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取风险评分失败');
  }
}

/** 从详情对话框打开审核 */
function handleAuditFromDetail() {
  detailDialogVisible.value = false;
  if (currentOrder.value) {
    auditForm.orderId = currentOrder.value.orderId;
    auditForm.riskScore = riskScore.value?.riskScore || 0;
    auditForm.passed = true;
    auditDialogVisible.value = true;
  }
}

/** 提交审核 */
function submitAudit() {
  auditFormRef.value?.validate((valid) => {
    if (valid) {
      const message = auditForm.passed ? '确认通过该订单的风控审核吗？' : '确认拒绝该订单吗？';
      ElMessageBox.confirm(message, '确认审核', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        riskAudit(auditForm)
          .then(() => {
            ElMessage.success('审核成功');
            auditDialogVisible.value = false;
            getList();
          })
          .catch(() => {
            ElMessage.error('审核失败');
          });
      });
    }
  });
}

/** 重置审核表单 */
function resetAuditForm() {
  auditFormRef.value?.resetFields();
  auditForm.orderId = 0;
  auditForm.passed = true;
  auditForm.riskScore = 0;
  auditForm.auditRemark = '';
  auditForm.rejectReason = '';
}

/** 获取评分等级样式 */
function getScoreClass(score: number): string {
  if (score >= 80) return 'text-success';
  if (score >= 60) return 'text-warning';
  return 'text-danger';
}

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.stat-card {
  text-align: center;

  .stat-label {
    font-size: 14px;
    color: #909399;
    margin-bottom: 10px;
  }

  .stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #303133;

    &.text-warning {
      color: #e6a23c;
    }

    &.text-info {
      color: #409eff;
    }
  }
}

.risk-score-panel {
  .score-display {
    text-align: center;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 8px;

    .score-label {
      font-size: 16px;
      color: #909399;
      margin-bottom: 10px;
    }

    .score-value {
      font-size: 48px;
      font-weight: bold;

      &.text-success {
        color: #67c23a;
      }

      &.text-warning {
        color: #e6a23c;
      }

      &.text-danger {
        color: #f56c6c;
      }
    }
  }
}

.text-danger {
  color: #f56c6c;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-info {
  color: #909399;
  font-size: 12px;
}

.text-secondary {
  color: #c0c4cc;
}
</style>
